package com.logistica.metropolitana.web.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import com.logistica.metropolitana.exceptions.UsuarioException;
import com.logistica.metropolitana.services.UsuarioService;
import com.logistica.metropolitana.web.views.UsuarioView;
/**
 * 
 * @author rioslore
 *
 */
public class LogisticaMetropolitanaAuthSuccessHandler implements AuthenticationSuccessHandler {
	
	private final Logger logger = LoggerFactory.getLogger(LogisticaMetropolitanaAuthSuccessHandler.class);
	
	private final String USER_VIEW = "USER_VIEW";

	@Autowired
	UsuarioService usuarioService;
	
	@Override
	public void onAuthenticationSuccess(HttpServletRequest request,
			HttpServletResponse response, Authentication authentication)
			throws IOException, ServletException {
		
		if (logger.isDebugEnabled()) {
			logger.debug("onAuthenticationSuccess -entering");
		}
		
		try {		
			UsuarioView usuarioView = usuarioService.getUsuarioByUsername(authentication.getName());
			HttpSession httpSession = request.getSession();
			httpSession.setAttribute(USER_VIEW, usuarioView);
		} catch (UsuarioException uException) {
			logger.error("Ocurrió un error al tratar de obtener al usuario {}", 
					authentication.getName(), uException);
			response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			response.sendRedirect(request.getContextPath() + "/error.html");
		}
		
		response.sendRedirect(request.getContextPath() + "/home.html");
		
		if (logger.isDebugEnabled()) {
			logger.debug("onAuthenticationSuccess -leaving");
		}
		
	}

}
